package com.industrial.white.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.alibaba.excel.util.StringUtils;

import com.industrial.common.security.utils.DictUtils;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.system.api.domain.SysDictData;
import com.industrial.system.api.domain.SysUser;
import com.industrial.system.api.model.LoginUser;
import com.industrial.white.domain.EnterpriseCount;
import com.industrial.white.domain.ProDomainCount;
import com.industrial.white.mapper.IndexMapper;
import com.industrial.white.service.IIndexService;
import com.industrial.white.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: TODO
 * @Date 2023/8/18 13:50
 * @Author SangGuangCan
 */
@Service
public class IndexServiceImpl implements IIndexService {

    @Autowired
    private IndexMapper indexMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    Map<String,String> enterTypeMap = new HashMap<>();
    Map<String,String> enterScaleMap = new HashMap<>();
    Map<String, String> bigTypeMap;
    Map<String, String> domainMap;

    @PostConstruct
    public void init(){
        enterTypeMap.put("1","国有及国有控股");
        enterTypeMap.put("2","私营");
        enterTypeMap.put("3","外商及港澳台投资");
        enterTypeMap.put("4","其他");

        enterScaleMap.put("1","大型");
        enterScaleMap.put("2","中型");
        enterScaleMap.put("3","小型");
        enterScaleMap.put("4","微型");

        List<SysDictData> bigTypeData = DictUtils.getDictCache("bus_national_economy_classification");

//        List<SysDictData> bigTypeData = dictDataMapper.selectDictDataByType("bus_national_economy_classification");
        bigTypeMap = bigTypeData.stream().collect(Collectors.toMap(k -> k.getDictValue(), v -> v.getDictLabel()));

        List<SysDictData> domainData = DictUtils.getDictCache("bus_pro_domain");
//        List<SysDictData> domainData = dictDataMapper.selectDictDataByType("bus_pro_domain");
        domainMap = domainData.stream().collect(Collectors.toMap(k -> k.getDictValue(), v -> v.getDictLabel()));

    }

    @Override
    public List<EnterpriseCount> getEnterpriseCount() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("当前用户可能没有登录");
        }
        SysUser user = loginUser.getSysUser();
        List<String> roles = user.getRoles().stream().map(item -> item.getRoleKey()).collect(Collectors.toList());

        if(user.isAdmin()){
            roles.add(CommonUtil.PROVINCE);
        }

        if(!(ArrayUtil.contains(roles.toArray(), CommonUtil.COUNTY) ||
                ArrayUtil.contains(roles.toArray(),CommonUtil.PROVINCE) ||
                ArrayUtil.contains(roles.toArray(),CommonUtil.CITY))){
            return new ArrayList<>();
        }
        Map<String,String> r = new HashMap<>(16);
        if(ArrayUtil.contains(roles.toArray(), CommonUtil.COUNTY)){
            r.put("COUNTY",user.getDistrictId());
        }else if(ArrayUtil.contains(roles.toArray(),CommonUtil.PROVINCE)) {
            r.put("PROVINCE",user.getProvinceId());
        }else if(ArrayUtil.contains(roles.toArray(),CommonUtil.CITY)) {
            r.put("CITY",user.getCityId());
        }

        if(ArrayUtil.contains(roles.toArray(), CommonUtil.COUNTY)){
            List<EnterpriseCount> enterpriseCounts = indexMapper.queryEnterpriseInfoByCountyId(r);
            return enterpriseCounts;
        }else{
            List<Map<String,Object>> reuslt = indexMapper.getCurrentAdEnterpriseCount(r);
            Map<Object, List<Map<String, Object>>> adIdMap = reuslt.stream().filter(item -> !Objects.isNull(item.get("adId"))).collect(Collectors.groupingBy(item -> item.get("adId")));
            List<EnterpriseCount> reList = new ArrayList<>();
            for(Map.Entry<Object,List<Map<String, Object>>> entry : adIdMap.entrySet()){
                EnterpriseCount temp = new EnterpriseCount();
                String adId = (String)entry.getKey();
                List<Map<String, Object>> value = entry.getValue();
                temp.setAdName((String) redisTemplate.opsForHash().get("adnbaseid",adId));
                System.out.println(temp.getAdName());
                if(value == null || value.isEmpty()){
                    temp.setCount(0);
                }else{
                    temp.setCount(value.size());
                }
                temp.setAreaId(adId);
                if(ArrayUtil.contains(roles.toArray(), CommonUtil.CITY)){
                    temp.getExt().put("ad","xian");
                }else if(ArrayUtil.contains(roles.toArray(),CommonUtil.PROVINCE)) {
                    temp.getExt().put("ad","shi");
                }
                reList.add(temp);
            }
            reList = reList.stream().sorted(Comparator.comparing(EnterpriseCount::getCount).reversed()).limit(7).collect(Collectors.toList());
            return reList;
        }
    }

    @Override
    public List<Map<String, Object>> getEnterprisePie() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("当前用户可能没有登录");
        }

        SysUser user = loginUser.getSysUser();
        List<String> roles = user.getRoles().stream().map(item -> item.getRoleKey()).collect(Collectors.toList());
        if(user.isAdmin()){
            roles.add(CommonUtil.PROVINCE);
        }
        if(!(ArrayUtil.contains(roles.toArray(), CommonUtil.COUNTY) ||
                ArrayUtil.contains(roles.toArray(),CommonUtil.PROVINCE) ||
                ArrayUtil.contains(roles.toArray(),CommonUtil.CITY))){
            return new ArrayList<>();
        }
        Map<String,String> r = new HashMap<>(16);
        if(ArrayUtil.contains(roles.toArray(), CommonUtil.COUNTY)){
            r.put("COUNTY",user.getDistrictId());
        }else if(ArrayUtil.contains(roles.toArray(),CommonUtil.PROVINCE)) {
            r.put("PROVINCE",user.getProvinceId());
        }else if(ArrayUtil.contains(roles.toArray(),CommonUtil.CITY)) {
            r.put("CITY",user.getCityId());
        }

        List<Map<String, Object>> result = indexMapper.getCurrentAdEnterpriseCount(r);
        Map<Object, List<Map<String, Object>>> enterTypeMap = result.stream().filter(item -> !Objects.isNull(item.get("enter_type"))).collect(Collectors.groupingBy(item -> item.get("enter_type")));
        List<Map<String,Object>> resultList = new ArrayList<>();
        for(Map.Entry<Object, List<Map<String, Object>>> entry : enterTypeMap.entrySet()) {
            Map<String, Object> temp = new HashMap<>(16);
            String key = (String) entry.getKey();
            temp.put("name", this.enterTypeMap.get(key));
            List<Map<String, Object>> value = entry.getValue();
            if (value == null || value.isEmpty()) {
                temp.put("value", 0);
            } else {
                temp.put("value", value.size());
            }
            resultList.add(temp);
        }
        return resultList;
    }

    @Override
    public Map<String,Object> getEnterpriseScaleCount() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("当前用户可能没有登录");
        }
        SysUser user = loginUser.getSysUser();
        List<String> roles = user.getRoles().stream().map(item -> item.getRoleKey()).collect(Collectors.toList());
        if(user.isAdmin()){
            roles.add(CommonUtil.PROVINCE);
        }
        if(!(ArrayUtil.contains(roles.toArray(), CommonUtil.COUNTY) ||
                ArrayUtil.contains(roles.toArray(),CommonUtil.PROVINCE) ||
                ArrayUtil.contains(roles.toArray(),CommonUtil.CITY))){
            return new HashMap<>();
        }
        Map<String,String> r = new HashMap<>(16);
        if(ArrayUtil.contains(roles.toArray(), CommonUtil.COUNTY)){
            r.put("COUNTY",user.getDistrictId());
        }else if(ArrayUtil.contains(roles.toArray(),CommonUtil.PROVINCE)) {
            r.put("PROVINCE",user.getProvinceId());
        }else if(ArrayUtil.contains(roles.toArray(),CommonUtil.CITY)) {
            r.put("CITY",user.getCityId());
        }
        List<Map<String, Object>> result = indexMapper.getCurrentAdEnterpriseCount(r);
        Map<String,Object> reusltMap = new HashMap<>();
        Map<Object, List<Map<String, Object>>> enterScale = result.stream().filter(item -> !Objects.isNull(item.get("enter_scale"))).collect(Collectors.groupingBy(item -> item.get("enter_scale")));

        List<Map<String, Object>> bigX = enterScale.get("1");
        List<Map<String, Object>> zX = enterScale.get("2");
        List<Map<String, Object>> xX = enterScale.get("3");
        List<Map<String, Object>> wX = enterScale.get("4");

        if(bigX == null || bigX.isEmpty()){
            reusltMap.put("daxing",0);
        }else{
            reusltMap.put("daxing",bigX.size());
        }

        if(xX == null || xX.isEmpty()){
            reusltMap.put("xiaoxing",0);
        }else{
            reusltMap.put("xiaoxing",xX.size());
        }
        if(zX == null || zX.isEmpty()){
            reusltMap.put("zhongxing",0);
        }else{
            reusltMap.put("zhongxing",zX.size());
        }
        if(wX == null || wX.isEmpty()){
            reusltMap.put("weixing",0);
        }else{
            reusltMap.put("weixing",wX.size());
        }
        return reusltMap;
    }

    @Override
    public List<EnterpriseCount> getEnterpriseBigType() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("当前用户可能没有登录");
        }
        SysUser user = loginUser.getSysUser();
        List<String> roles = user.getRoles().stream().map(item -> item.getRoleKey()).collect(Collectors.toList());
        if(user.isAdmin()){
            roles.add(CommonUtil.PROVINCE);
        }
        if(!(ArrayUtil.contains(roles.toArray(), CommonUtil.COUNTY) ||
                ArrayUtil.contains(roles.toArray(),CommonUtil.PROVINCE) ||
                ArrayUtil.contains(roles.toArray(),CommonUtil.CITY))){
            return new ArrayList<>();
        }
        Map<String,String> r = new HashMap<>(16);
        if(ArrayUtil.contains(roles.toArray(), CommonUtil.COUNTY)){
            r.put("COUNTY",user.getDistrictId());
        }else if(ArrayUtil.contains(roles.toArray(),CommonUtil.PROVINCE)) {
            r.put("PROVINCE",user.getProvinceId());
        }else if(ArrayUtil.contains(roles.toArray(),CommonUtil.CITY)) {
            r.put("CITY",user.getCityId());
        }
        List<Map<String, Object>> result = indexMapper.getCurrentAdEnterpriseCount(r);
        Map<Object, List<Map<String, Object>>> enterCategory = result.stream().filter(item -> !Objects.isNull(item.get("enter_category"))).collect(Collectors.groupingBy(item -> item.get("enter_category")));
        List<EnterpriseCount> resultList = new ArrayList<>();
        for(Map.Entry<Object, List<Map<String, Object>>> entry : enterCategory.entrySet()){
            EnterpriseCount enterpriseCount = new EnterpriseCount();
            String key = (String)entry.getKey();
            List<Map<String, Object>> value = entry.getValue();
            enterpriseCount.setAdName(bigTypeMap.get(key));
            enterpriseCount.setBigType(key);
            if(value == null || value.isEmpty()){
                enterpriseCount.setCount(0);
            }else{
                enterpriseCount.setCount(value.size());
            }
            resultList.add(enterpriseCount);
        }
        resultList = resultList.stream()
                .sorted(Comparator.comparing(EnterpriseCount::getCount).reversed()).limit(8)
                .collect(Collectors.toList());

        for(int i = 0; i < resultList.size();i++){
            resultList.get(i).setXh( i + 1);

        }

        return resultList;
    }

    @Override
    public List<ProDomainCount> getDomainCount() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("当前用户可能没有登录");
        }
        SysUser user = loginUser.getSysUser();
        List<String> roles = user.getRoles().stream().map(item -> item.getRoleKey()).collect(Collectors.toList());
        if(user.isAdmin()){
            roles.add(CommonUtil.PROVINCE);
        }
        if(!(ArrayUtil.contains(roles.toArray(), CommonUtil.COUNTY) ||
                ArrayUtil.contains(roles.toArray(),CommonUtil.PROVINCE) ||
                ArrayUtil.contains(roles.toArray(),CommonUtil.CITY))){
            return new ArrayList<>();
        }
        Map<String,String> r = new HashMap<>(16);
        if(ArrayUtil.contains(roles.toArray(), CommonUtil.COUNTY)){
            r.put("COUNTY",user.getDistrictId());
        }else if(ArrayUtil.contains(roles.toArray(),CommonUtil.PROVINCE)) {
            r.put("PROVINCE",user.getProvinceId());
        }else if(ArrayUtil.contains(roles.toArray(),CommonUtil.CITY)) {
            r.put("CITY",user.getCityId());
        }
        List<ProDomainCount> count = indexMapper.getDomainCountNew(r);
        int allEnterCount = indexMapper.getAllEnterCount(r);

        List<ProDomainCount> resultList = new ArrayList<>();
        for(int i =0;i<count.size();i++){
            ProDomainCount proDomainCount = count.get(i);
            if(StringUtils.isBlank(proDomainCount.getProDomainKey())){
                continue;
            }
            String sl = proDomainCount.getSl();
            double zb = Double.valueOf(sl) / Double.valueOf(allEnterCount) * 100;
            proDomainCount.setZb(String.format("%.02f", zb));
            String domainName = this.domainMap.get(proDomainCount.getProDomainKey());
            proDomainCount.setSslyStr(domainName);
            resultList.add(proDomainCount);
        }
        resultList = resultList.stream().sorted(Comparator.comparing(ProDomainCount::getSl).reversed()).limit(6).collect(Collectors.toList());
        return resultList;
//        List<ProDomain> domainCount = indexMapper.getDomainCount(r);
//        Map<String, List<ProDomain>> domainMap = domainCount.stream().filter(item -> !Objects.isNull(item.getProDomain())).collect(Collectors.groupingBy(ProDomain::getProDomain));
//        List<ProDomain> domainArgs = new ArrayList<>();
//        for(Map.Entry<String, List<ProDomain>> entry : domainMap.entrySet()){
//            List<ProDomain> value = entry.getValue();
//            domainArgs.addAll(value);
//        }
//        double size = domainArgs.size();
//        if(size == 0){
//            return null;
//        }
//        List<EnterpriseCount> resultList = new ArrayList<>();
//        for(Map.Entry<String, List<ProDomain>> entry : domainMap.entrySet()){
//            EnterpriseCount enterpriseCount = new EnterpriseCount();
//            String key = entry.getKey();
//            double count = 0;
//            List<ProDomain> value = entry.getValue();
//            if(value == null || value.isEmpty()){
//                count = 0;
//            }else{
//                count = value.size();
//            }
//            List<ProDomain> quChong = value.stream().distinct().collect(Collectors.toList());
//            if(quChong == null || quChong.isEmpty()){
//                enterpriseCount.setCount(0);
//            }else{
//                enterpriseCount.setCount(quChong.size());
//            }
//
//            double baifenbi = (count / size) * 100;
//            BigDecimal bigDecimal = new BigDecimal(baifenbi);
//            enterpriseCount.setBaifenbi(bigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
//            String domainName = this.domainMap.get(key);
//            if(domainName != null){
//                if(domainName.contains("其他")){
//                    enterpriseCount.setAdName("其他");
//                }else{
//                    enterpriseCount.setAdName(domainName);
//                }
//            }
//            enterpriseCount.setProDomainKey(key);
//            resultList.add(enterpriseCount);
//        }
//        resultList = resultList.stream().sorted(Comparator.comparing(EnterpriseCount::getBaifenbi).reversed()).limit(6).collect(Collectors.toList());
//        return resultList;
    }
}
